<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Models\DealLog;
use App\Models\Shop;
use App\Models\ShopRole;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Closure;

class ApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!($token = $request->header('accessToken'))){
            return response()->json([
                'code' => 1024,
                'message' => '缺少参数accessToken',
            ]);
        }
        if (strpos($token, '.') === false) {
            return response()->json([
                'code' => 1024,
                'message' => 'accessToken格式错误',
            ]);
        }
        
        list($uid, $token) = explode('.', $request->header('accessToken'));

        $user = User::where('id', $uid)->where('accessToken', $token)->with(['wallet', 'member'])->first();
        if (!$user) {
            return response()->json([
                'code' => 1025,
                'message' => '请重新登录',
            ]);
        }
        $now = Carbon::now();
        $atExpiredTime = $user->atExpiredTime;
        if($now->gt($atExpiredTime)){
            return response()->json([
                'code' => 1024,
                'message' => 'accessToken已过期，请重新登录',
            ]);
        }
        //被禁用做判断
        if ($user->status == User::STATUS_DISABLED) {
            return response()->json([
                'code' => 401,
                'message' => '您已被禁用！',
            ]);
        }
        //会员逻辑
        if ($user->is_member && $user->member_end_time<time()) {
            
            $user->is_member = 0;
            $user->level = 0;
            $user->member_start_time = 0;
            $user->member_end_time = 0;
            $user->fid = 0;
            $user->shop_id = 0;

            //退还押金到余额
            $wallet = $user->wallet;
            $deposit = $wallet->deposit;
            $wallet->money = $wallet->money+$deposit;
            $wallet->deposit = 0;
            DB::beginTransaction();
            try {
                $user->save();
                $wallet->save();
                DealLog::add_log($user->id, 0, $deposit, 1, '退还会员押金至余额');
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
            }

        }

        $request->user = $user;
        return $next($request);
    }
}
